package com.common.baselibrary.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.StringRes;

import com.common.baselibrary.BaseLibraryApplication;
import com.common.baselibrary.R;


/**
 * Toast提示辅助类
 * Created by Administrator
 * 2019/10/15.
 */
public final class ToastToolsHelper {

    @SuppressLint("StaticFieldLeak")
    private static ToastToolsHelper instance;
    private long lastToastTimeMillis;
    private static final int interval = 1000;
    private Context context;

    private ToastToolsHelper(Context context) {
        this.context = context;
    }

    static {
        instance = new ToastToolsHelper(BaseLibraryApplication.getBaseApplication());
    }


    /**
     * 创建 Toast 并设置布局
     *
     * @param context application context
     */
    private Toast createToast(Context context, CharSequence text) {
        Toast toast = new Toast(context.getApplicationContext());
        float density = DimensionHelper.getDensity();
        int horizontalPadding = (int) (density * 10);
        int verticalPadding = (int) (density * 5);
        TextView textView = new TextView(context.getApplicationContext());
        textView.setTextSize(14f);
        textView.setTextColor(0xffffffff);
        textView.setBackgroundResource(R.drawable.bg_toast);
        textView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
        textView.setText(text);
        toast.setView(textView);
        return toast;
    }

    /**
     * 显示 Toast
     *
     * @param resId 需要显示的字符串资源id
     */
    public static void show(@StringRes int resId) {
        instance.showText(resId);
    }

    /**
     * 显示 Toast
     *
     * @param text 需要显示的文本
     */
    public static void show(CharSequence text) {
        instance.showText(text, 2);
    }

    /**
     * 显示 Toast
     *
     * @param resId 字符串资源id
     */
    private void showText(@StringRes int resId) {
        showText(context.getString(resId), 3);
    }

    private void showText(CharSequence text, int logExtraLevel) {
        if (text == null || !validateTimeInterval())
            return;
        createToast(context, text).show();
        LogHelper.w("Toast信息", text, logExtraLevel);
    }

    private boolean validateTimeInterval() {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastToastTimeMillis < interval) return false;
        lastToastTimeMillis = currentTimeMillis;
        return true;
    }

}